<script setup>
	import { onLoad } from '@dcloudio/uni-app'
	import { ref, computed, getCurrentInstance } from 'vue'
	import { getLabel } from '@/utils/common'
	import { getDicts } from '@/api/login'
	import { getSortingListDetail, sortingListConfirm } from '@/api/inventory'
	
	const instance = getCurrentInstance().proxy
	const loading = ref(false)
	const query = ref({goodsId: '', onlyUsable: true, current: 1, size: 20})
	const triggered = ref(false)
	const loadStatus = ref('loadmore')
	const total = ref(0)
	const uForm = ref(null)
	const form = ref({items: []})
	const rules = ref({})
	const unitColumns = ref([])
	const preData = ref({num: 0})
	const curNum = computed(() => {
		return form.value.items.reduce((total, item) => {
			return total + item.num
		}, 0)
	})
	
	function refreshList() {
		if(loadStatus.value === 'loading') return
		loadStatus.value = 'loading'
		triggered.value = true
		form.value.items = []
		query.value.current = 1
		const goodsId = query.value.goodsId
		getSortingListDetail(query.value).then(res => {
			if(query.value.goodsId !== goodsId) return
			let result = res.result || {}
			let data = result.records || []
			data.forEach(item => item.num = 0)
			total.value = Number(result.total)
			form.value.items = data
			triggered.value = false
			let curLength = form.value.items.length || 0
			loadStatus.value = curLength === total.value? 'nomore' : 'loadmore'
		}).catch(() => {
			triggered.value = false
			loadStatus.value = 'loadmore'
		})
	}
	function lowerList(noReplace = true) {
		if(form.value.items.length < total.value || !noReplace){
			loadStatus.value = 'loading'
			query.value.current ++
			getSortingListDetail(query.value).then(res => {
				let result = res.result || {}
				let data = result.records || []
				data.forEach(item => item.num = 0)
				total.value = Number(result.total)
				if(noReplace) {
					form.value.items.push(...data)
				} else {
					const preList = form.value.items.slice(0, (query.value.current - 1) * query.value.size)
					form.value.items = preList.concat(data)
				}
				let curLength = form.value.items.length || 0
				loadStatus.value = curLength === total.value? 'nomore' : 'loadmore'
			}).catch(() => {
				query.value.current --
				loadStatus.value = 'loadmore'
			})
		}
	}
	function restore() {
		triggered.value = false
	}
	function refreshItem(id) {
		let index = form.value.items.findIndex(item => item.inventoryId === id)
		if(index != -1) {
			query.value.current = Math.floor(index / query.value.size)
			lowerList(false)
		}
	}
	function getDictLabel(key, value) {
		switch(key) {
			case 'unit': return getLabel(unitColumns.value, value);
			default: return ''
		}
	}
	function goCancel() {
		uni.navigateBack()
	}
	function goConfirm() {
		uForm.value.validate().then(() => {
			loading.value = true
			let params = form.value.items.reduce((arr, item) => {
				arr.push({
					orderId: preData.value.orderId,
					orderCode: preData.value.code,
					orderItemId: preData.value.itemId,
					inventoryId: item.inventoryId,
					sorted: item.num,
				})
				return arr
			}, [])
			sortingListConfirm(params).then(res => {
				uni.showToast({icon: 'success', title: '提交成功'})
				loading.value = false
				setTimeout(() => { uni.navigateBack() }, 200)
			}).catch(() => loading.value = false)
		})
	}
	
	onLoad(() => {
		const eventChannel = instance.getOpenerEventChannel()
		eventChannel.on('info', params => {
			query.value.goodsId = params.goodsId
			preData.value = params
			getDicts('sys_good_unit').then(res => {
				unitColumns.value = res.result?.records || []
				triggered.value = true
			})
		})
	})
</script>

<template>
	<view class="app-container">
		<view class="app-head">
			<view class="total-box">
				<view>
					<text>需求量：</text>
					<text class="value">{{preData.num || 0}}</text>
				</view>
				<view>
					<text>分拣量：</text>
					<text class="value">{{curNum}}</text>
				</view>
			</view>
			<view class="head-tip">商品信息</view>
		</view>
		<scroll-view scroll-y="true" class="app-content" refresher-enabled :refresher-triggered="triggered" @refresherrefresh="refreshList" lower-threshold="10" @scrolltolower="lowerList" @refresherrestore="restore">
			<uv-form :model="form" :rules="rules" ref="uForm" labelWidth="406" labelAlign="right">
				<view class="form-box">
					<view class="content" v-if="form.items.length">
						<view class="list-box" v-for="(item, index) in form.items" :key="item.itemId">
							<view class="box-head">
								<text>批次号：{{item.batchCode}}</text>
								<text>可用库存：{{item.usable || 0}}</text>
							</view>
							<view class="box-info">
								<text>入库时间：{{item.createTime || '--'}}</text>
								<text>商品单位：{{getDictLabel('unit', item.goodsUnit) || '--'}}</text>
							</view>
							<uv-form-item label="分拣数量：" prop="num">
								<view class="custom-content">
									<uv-number-box v-model="item.num" min="0" :max="item.usable" integer inputWidth="96" bgColor="#FFFFFF" buttonSize="64">
										</uv-number-box>
								</view>
							</uv-form-item>
						</view>
					</view>
					<empty text="没有找到商品信息" v-else-if="loadStatus != 'loading'"></empty>
				</view>
			</uv-form>
		</scroll-view>
		<view class="form-bottom theme-btn">
			<uv-button shape="circle" :custom-style="{width: '338rpx;'}" text="取消" @click="goCancel" :disabled="loading"></uv-button>
			<uv-button type="primary" shape="circle" :custom-style="{width: '338rpx'}" text="确定" @click="goConfirm" :disabled="loading  || loadStatus === 'loading'">
				</uv-button>
		</view>
	</view>
</template>

<style lang="scss" scoped>
	.app-container{
		padding-top: 2rpx;
		height: 100vh;
		background-color: #fff;
		.app-head{
			.total-box{
				height: 96rpx;
				padding: 0 110rpx;
				background-color: #DEECFF;
				display: flex;
				justify-content: space-between;
				align-items: center;
				gap: 16rpx;
				.value{
					font-size: var(--theme-lg);
					color: $uv-primary;
					font-weight: 600;
				}
			}
			.head-tip{
				height: 80rpx;
				padding: 0 32rpx;
				display: flex;
				align-items: center;
				position: relative;
				font-size: var(--theme-lg);
				font-weight: 600;
				&::before{
					content: "";
					position: absolute;
					top: 28rpx;
					left: 16rpx;
					width: 8rpx;
					height: 30rpx;
					background-color: $uv-primary;
				}
			}
		}
		.app-content{
			width: 100%;
			height: calc(100% - 292rpx);
			height: calc(100% - 292rpx - constant(safe-area-inset-bottom));
			height: calc(100% - 292rpx - env(safe-area-inset-bottom));
		}
		.form-box{
			padding: 0 32rpx 16rpx;
			margin-bottom: 14rpx;
			.content{
				.custom-content{
					width: 100%;
				}
				.text-no{
					color: #9CA0A6;
				}
				::v-deep .uv-form-item__body{
					padding: 18rpx 0;
				}
				::v-deep .uv-form-item__body__left__content__required{
					left: unset;
					right: -8rpx;
				}
				::v-deep .uv-number-box__minus .uv-icon__icon{
					font-size: 28rpx !important;
				}
				::v-deep .uv-number-box__plus .uv-icon__icon{
					font-size: var(--theme-df) !important;
					color: $uv-primary !important;
				}
			}
			.list-box{
				padding: 24rpx;
				background-color: #F5F7FA;
				border-radius: 8rpx;
				border: 2rpx solid #F5F5F5;
				.box-head{
					display: flex;
					justify-content: space-between;
					align-items: center;
					font-weight: 600;
				}
				.box-info{
					margin-top: 16rpx;
					display: flex;
					justify-content: space-between;
					align-items: center;
					gap: 16rpx;
					font-size: var(--theme-sm);
				}
			}
			.list-box + .list-box{
				margin-top: 16rpx;
			}
		}
		.form-bottom{
			width: 100%;
			height: 116rpx;
			height: calc(constant(safe-area-inset-bottom) + 116rpx);
			height: calc(env(safe-area-inset-bottom) + 116rpx);
			padding: 16rpx 24rpx;
			padding-bottom: calc(constant(safe-area-inset-bottom) + 16rpx);
			padding-bottom: calc(env(safe-area-inset-bottom) + 16rpx);
			background-color: #FFFFFF;
			box-shadow: 0rpx -8rpx 8rpx 0rpx rgba(0,0,0,0.04);
			display: flex;
			align-items: center;
			gap: 24rpx;
		}
		.popup-box{
			width: 686rpx;
			padding: 32rpx;
			.popup-title{
				font-weight: 600;
				font-size: var(--theme-xl);
				line-height: var(--theme-xl-line);
				text-align: center;
			}
			.popup-content{
				padding: 30rpx 48rpx 48rpx;
				color: #6C6F73;
				text-align: center;
			}
			.popup-bottom{
				display: flex;
				justify-content: center;
				align-items: center;
				gap: 32rpx;
			}
		}
	}
</style>